package com.yami.shop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.Post;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.param.CreatePostParam;
import com.yami.shop.bean.param.PostsQuery;
import com.yami.shop.bean.vo.PostsVO;
import com.yami.shop.dao.PostsMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.service.AuditLogService;
import com.yami.shop.service.LikeService;
import com.yami.shop.service.PostService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用于存储用户发布的动态，包括文字、图片和视频 服务实现类
 * </p>
 *
 * @author EXiaoKe
 * @since 2025-04-14
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class PostServiceImpl extends ServiceImpl<PostsMapper, Post> implements PostService {

    private final AuditLogService auditLogService;

    @Resource
    private UserMapper userMapper;
    // 原方法修改后示例

    @Resource
    private LikeService likeService;

    @Resource
    private PostsMapper postsMapper;
    @Override
    public IPage<PostsVO> getPostPage(Page<Post> page, PostsQuery  query) {
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<Post>()
                .like(StrUtil.isNotBlank(query.getContent()), Post::getContent, query.getContent());

        // 1. 执行原始分页查询（Post表）
        Page<Post> postPage = baseMapper.selectPage(page, wrapper);


        // 2. 提取所有userId准备批量查询
        List<String> userIds = postPage.getRecords().stream()
                .map(Post::getUserId)
                .distinct()
                .collect(Collectors.toList());

        final Map<String, String> userNickNameMap = userIds.isEmpty()
                ? Collections.emptyMap()  // 直接返回空 Map，无需初始化后修改
                : userMapper.selectBatchIds(userIds).stream()
                .collect(Collectors.toMap(User::getUserId, User::getNickName));

        return postPage.convert(post -> {
            PostsVO vo = new PostsVO();

            BeanUtils.copyProperties(post, vo);
            vo.setNickName(userNickNameMap.getOrDefault(post.getUserId(), "未知用户")); // ✅ 变量隐式 final

            // 原统计查询保持不动（需根据实际情况考虑是否优化）
            log.info("统计查询点赞数：{}", likeService.getLikesCount(post.getPostId()));
            vo.setLikeCount(likeService.getLikesCount(post.getPostId()));
            vo.setCommentCount(baseMapper.selectCommentCount(post.getPostId()));

            return vo;
        });
    }

    @Override
    @Transactional
    public void auditPost(Long postId, String auditAction, String reason) {
        Post post = getById(postId);
        post.setStatus("approved".equals(auditAction) ?
                Post.PostStatus.APPROVED : Post.PostStatus.REJECTED);
        updateById(post);

        auditLogService.logAudit(postId, auditAction, reason);
    }

    /**
     * 删除帖子
     *
     * @param postId
     * @param userId
     */
    @Override
    public void deletePost(Long postId, String userId) {

    }

    /**
     * 创建新帖子
     *
     * @param param
     * @return
     */
    @Override
    public Long createPost(CreatePostParam param) {
        Post post = new Post();
        post.setContent(param.getContent());
        post.setMediaUrl(param.getMediaUrl());
        post.setType(Post.PostType.TEXT);
        post.setUserId(param.getUserId());
        if (postsMapper.insert(post) > 0) {
            return post.getPostId();
        }
        return null;
    }
}